package org.ucas.faker.web.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ucas.faker.web.dao.QueryDao;
import org.ucas.faker.web.entity.Query;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class QueryService {

  @Autowired
  private QueryDao queryDao;

  public Query load(long id) {
    return queryDao.findOne(id);
  }

  public Page<Query> page(long userId, Integer pageNumber,Integer pageSize, Integer type) {
    if(pageNumber == null) pageNumber = 1;
    if(pageSize == null) pageSize = 20;

    List<Sort.Order> orders = new ArrayList<Sort.Order>(){{
      add(new Sort.Order(Sort.Direction. DESC, "createAt"));
    }};

    PageRequest page = new PageRequest(pageNumber-1,pageSize,new Sort(orders));

    return type == null? queryDao.findByUserId(userId,page) : queryDao.findByUserIdAndType(userId,type,page);
  }

  public Query create(Query query) {
    return queryDao.save(query);
  }

  public void delete(long id) {
    queryDao.delete(id);
  }
}
